package com.itheima.health.h5.controller;

import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Order;
import com.itheima.health.service.OrderService;
import com.itheima.health.utils.pay.XmlUtil;
import com.itheima.health.utils.redis.RedisUtil;
import com.itheima.health.utils.resources.RedisConstant;
import com.itheima.health.utils.resources.RedisMessageConstant;
import com.itheima.health.utils.sms.SmsUtils;
import com.itheima.health.utils.sms.ValidateCodeUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Log4j2
public class OrderController {

    @Reference(mock= "com.itheima.health.mock.OrderServiceMock"  ,timeout = 10000)
    private OrderService orderService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping("order/sendMessage/{telephone}")
    public Result sendMessage(@PathVariable("telephone")String  telephone){
        //  存放 redis    阿里云发送短信
        String code = ValidateCodeUtils.generateValidateCode(4);
        System.out.println("code = " + code);
        redisTemplate.opsForValue().set(RedisMessageConstant.SENDTYPE_ORDER+telephone,code,90, TimeUnit.SECONDS);
       // mq  发送发短信内容 消息形式 投递 mq  队列上
        Map map = new HashMap();
        map.put("telephone",telephone);
        map.put("code",code);
       // rabbitTemplate.convertAndSend("heima_health",map);
        return  new Result(code);
    }

    @GetMapping("order/findOrderInfoById/{id}")
    public Result findOrderInfoById(@PathVariable("id")String id){
        return new Result(orderService.findOrderInfoById(Long.parseLong(id)));
    }

    @PostMapping("order/add")
    public Result add(@RequestBody Map map){
        Order order = orderService.add(map);
        if (order.getId()!=null){
            sendDelayMessage(order.getId(),60000L);
        }
        return new Result(order);
    }

    @GetMapping("order/payById/{id}")
    public Result payById(@PathVariable("id") String id) {
        System.out.println("id = " + id);
        return new Result(orderService.payById(Long.parseLong(id)));
    }

    @PostMapping("order/payNotify")
    public void payNotify(@RequestBody String xml, HttpServletResponse response) throws Exception {
        System.out.println("xml = " + xml);
        Map<String, String> map = XmlUtil.xmlToMap(xml);
        String oid = (String) map.get("out_trade_no");
        Order order = new Order();
        order.setId(Long.parseLong(oid));
        order.setIsPay(1);
        orderService.updateById(order);
        HashMap<String, String> result = new HashMap<>();
        result.put("return_code", "SUCCESS");
        result.put("return_msg", "OK");
        // 将map转为xml
        xml = XmlUtil.mapToXml(result);
        response.setContentType("application/xml;charset=utf-8");
        response.getWriter().write(xml);
    }

    @GetMapping("order/checkOrderStatus/{id}")
    public Result checkOrderStatus(@PathVariable("id") String id) {
        return new Result(orderService.checkOrderStatus(Long.parseLong(id)));
    }

    @GetMapping("order/deleteOrderById/{id}")
    public Result deleteOrderById(@PathVariable("id") String id) {
        return new Result(orderService.removeById(Long.parseLong(id)));
    }


    /**
     * 发送延时消息
     *
     * @param msg
     */
    public void sendDelayMessage(Object msg, Long delayTime) {
        rabbitTemplate.convertAndSend("delay_exchange", "delay_key", msg,
                message -> {
                    //设置延迟时间
                    message.getMessageProperties().setHeader("x-delay", delayTime);
                    return message;
                });
        log.info("发送延迟消息：{}，延时：{}毫秒", msg, delayTime);
    }



}
